package com.agrm.rabc.controller;

import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.Resource;
import com.agrm.model.rabc.pojo.ResourceSearchBean;
import com.agrm.rabc.service.ResourceService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api/v1/resources", produces = MediaType.APPLICATION_JSON_VALUE)
public class ResourceApi {
    private ResourceService resourceService;

    @Autowired
    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @GetMapping
    public ResponseResult findAll(ResourceSearchBean rsb,
                                  @RequestParam(defaultValue = "1") Integer pageNo,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Resource> page = new Page<>(pageNo, pageSize);
        page = resourceService.findAll(rsb, page);
        return ResponseResult.okResult(page);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        Resource resource = resourceService.findById(id);
        if (resource == null) {
            return ResponseResult.errorResult(-1,"未查询到指定编号的资源");
        } else {
            return ResponseResult.okResult(resource);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody Resource resource) {
        boolean success = resourceService.save(resource);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"保存资源失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody Resource resource) {
        boolean success = resourceService.update(resource);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"修改资源失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        Objects.requireNonNull(ids);

        int count = resourceService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除资源失败");
        }
    }
}
